package com.app.action;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.app.entity.User;
import com.app.service.UserService;

@SuppressWarnings("serial")
@Scope("prototype")
@Controller
public class UserAction extends BaseActionSupport<User>{
	private User user = new User();
	private String newPassword;
	
	@Autowired
	private UserService userService;

	public String login(){
		if (userService.login(user)) {
			logger.debug("登陆成功");
			ServletActionContext.getRequest().getSession().setAttribute("username", user.getName());
			
			return SUCCESS;
		}
		
		logger.debug("登陆失败");
		addActionError("登陆失败");
		
		return "loginJsp";
	}
	
	public String logout(){
		ServletActionContext.getContext().getSession().remove("username");
		return "loginJsp";
	}

	protected void prepareModel() throws Exception {
		String username = ServletActionContext.getContext().getSession().get("username").toString();
		user.setName(username);
		user = userService.findUserByParameter(user);
	}

	public String saveOrUpdate() throws Exception {
		if(userService.updatePassword(user, newPassword)){
			logger.debug("修改密码成功！");
			addActionMessage("修改密码成功！");
			return SUCCESS;
		}
		
		logger.debug("修改密码失败！");
		addActionMessage("修改密码失败！");
		return SUCCESS;
	}

	public User getModel() {
		return user;
	}

	public String getNewPassword() {
		return newPassword;
	}

	public void setNewPassword(String newPassword) {
		this.newPassword = newPassword;
	}
}
